<template>
  <!-- v-model="checkAll"
      :indeterminate="isIndeterminate"
      @change="handleCheckAllChange" -->
  <div class="alloc-resource" v-for="c in categories" :key="c.id">
    <el-checkbox
      @change="change(c)"
      v-model="c.checkAll"
      :indeterminate="c.indeterminate"
      >{{ c.name }}</el-checkbox
    >
    <el-checkbox-group v-model="c.checkedId" @change="subChange(c)">
      <el-checkbox v-for="r in c.children" :key="r.id" :label="r.id">{{
        r.name
      }}</el-checkbox>
    </el-checkbox-group>
  </div>
</template>
<script setup lang="ts">
import {
  getAllResourceCategoryApi,
  getAllResouceApoi,
  getResourceListByRoleIdApi,
} from "@/api";
import { ref } from "vue";
import { useRoute } from "vue-router";
const route = useRoute();

const categories = ref<AllocResouceData[]>([]);

// 传入一个Promise对象数组，等待所有Promise对象执行完毕，再走then
Promise.all([
  getAllResourceCategoryApi(),
  getAllResouceApoi(),
  getResourceListByRoleIdApi(parseInt(route.query.id as string)),
]).then(([catetoryRes, resourceRes, roleResourceRes]) => {
  if (
    catetoryRes.code === 200 &&
    resourceRes.code === 200 &&
    roleResourceRes.code === 200
  ) {
    categories.value = catetoryRes.data as AllocResouceData[];
    // 构建一个父子关系，用于在页面上进行渲染
    categories.value.forEach((c) => {
      resourceRes.data.forEach((r) => {
        if (r.categoryId === c.id) {
          // 找到了父子关系 ，把 r push 到 c 的 children
          if (!c.children) {
            c.children = [];
          }
          c.children.push(r);
        }
      });
      if (!c.checkedId) {
        c.checkedId = [];
      }
      // 把后端返回 当前角色 的 旧的 资源数据 ， 把id 放到 c 的 checkedId 数组里面
      roleResourceRes.data.forEach((rr) => {
        if (rr.categoryId === c.id) {
          c.checkedId!.push(rr.id);
        }
      });
      // 继续确定 全选 还是 半选
      // 是否全选
      c.checkAll = c.children?.length === c.checkedId?.length;
      // 半选
      c.indeterminate =
        c.checkedId!.length > 0 && c.checkedId!.length < c.children!.length;
    });
  }
});

const subChange = (p: AllocResouceData) => {
  // 判断是否全选和半选
  p.checkAll = p.children?.length === p.checkedId?.length;
  p.indeterminate =
    p.checkedId!.length > 0 && p.checkedId!.length < p.children!.length;
};

const change = (p: AllocResouceData) => {
  p.checkAll
    ? (p.checkedId = p.children?.map((c) => c.id))
    : (p.checkedId = []);
  p.checkAll = p.children?.length === p.checkedId?.length;
  p.indeterminate =
    p.checkedId!.length > 0 && p.checkedId!.length < p.children!.length;
};
</script>
<style lang="less" scoped>
.alloc-resource {
  padding: 20px;
  box-shadow: 0 0 4px 2px #ccc;
  border-radius: 10px;
  margin-bottom: 20px;
}
</style>
